﻿import 'dart:async';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'sleep_state.dart';
import '../../core/controllers/ring_controller.dart';
import '../../services/ring_service.dart';
import '../../core/repository/default_api.dart';
import '../../services/device_storage_service.dart';
import '../../services/device_sn_manager.dart';

/// 睡眠页控制器
class SleepLogic extends GetxController {
  /// 状态实例
  final SleepState state = SleepState();

  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  // 监听器是否已设置的标志
  bool _listenersSetup = false;

  @override
  void onInit() {
    super.onInit();
    print('🚀 睡眠控制器开始初始化');

    // 首先设置监听器
    _setupSleepDataListeners();

    // 然后初始化睡眠数据
    initializeSleepData();

  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    // 清理资源
  }

  /// 初始化睡眠数据
  void initializeSleepData() {
    print('😴 初始化睡眠数据，设备连接状态: ${ringController.isConnected}');

    // 初始化空状态
    _initializeEmptyState();

    // 检查是否已有睡眠数据
    _checkExistingSleepData();

    // 【修改】等待数据上报完成后再加载睡眠详情数据
    if (ringController.isConnected || _hasDeviceRecord()) {
      print('🔗 设备已连接或有连接记录，等待数据上报完成后加载睡眠详情');
      _waitForDataReportAndLoadDetails();
    } else {
      print('📱 设备未连接且无连接记录，显示空状态');
    }
    
    // 如果设备未连接，设置连接状态监听
    if (!ringController.isConnected) {
      print('📱 设备未连接，等待连接...');
      _setupConnectionListener();
    } else {
      print('🔗 设备已连接，等待自动数据同步...');
    }
  }
  
  /// 等待数据上报完成后加载睡眠详情
  Future<void> _waitForDataReportAndLoadDetails() async {
    try {
      final ringService = Get.find<RingService>();
      
      // 如果数据已经上报完成，直接加载
      if (ringService.dataReportCompleted) {
        print('✅ 数据已上报完成，立即加载睡眠详情');
        await _loadSleepDetailData();
        return;
      }
      
      // 否则等待数据上报完成
      print('⏳ 等待数据上报完成...');
      
      // 使用 ever 监听数据上报完成事件
      ever(ringService.dataReportCompletedRx, (completed) async {
        if (completed) {
          print('🎉 数据上报完成，开始加载睡眠详情');
          await _loadSleepDetailData();
        }
      });
      
      // 设置超时保护（最多等待 35 秒）
      Future.delayed(const Duration(seconds: 35), () async {
        if (!ringService.dataReportCompleted) {
          print('⚠️ 等待数据上报超时，强制加载睡眠详情');
          await _loadSleepDetailData();
        }
      });
    } catch (e) {
      print('❌ 等待数据上报异常: $e，直接加载睡眠详情');
      await _loadSleepDetailData();
    }
  }

  /// 检查是否已有睡眠数据
  void _checkExistingSleepData() {
    final existingSleepData = ringController.sleepData;
    if (existingSleepData != null) {
      print('📊 发现已有睡眠数据，立即更新状态');
      updateSleepDataFromRealData(existingSleepData);
    } else {
      print('📭 暂无睡眠数据');
    }
  }

  /// 初始化空状态
  void _initializeEmptyState() {
    state.dailySleepScore.value = 0;
    state.dailySleepTime.value = '--';
    state.dailyBedTime.value = '--';
    state.dailySleepLatency.value = 0;

    state.weeklySleepScore.value = 0;
    state.weeklySleepTime.value = '--';
    state.weeklyBedTime.value = '--';
    state.weeklySleepLatency.value = 0;

    state.monthlySleepScore.value = 0;
    state.monthlySleepTime.value = '--';
    state.monthlyBedTime.value = '--';
    state.monthlySleepLatency.value = 0;

    print('📝 睡眠状态已初始化为空值');
  }

  /// 设置连接状态监听器
  void _setupConnectionListener() {
    // 【修改】不再手动查询睡眠数据，只监听连接状态
    // Kotlin 端的 fetchAllDeviceData() 会在连接成功后自动查询所有数据
    Timer.periodic(const Duration(seconds: 2), (timer) {
      if (ringController.isConnected &&
          ringController.connectionState == RingConnectionState.connected) {
        print('🔗 设备连接成功，等待自动数据同步...');
        timer.cancel(); // 停止定时器
        // 数据会通过监听器自动更新到 UI，不需要手动查询
      }
    });
  }

  /// 查询睡眠相关数据
  void querySleepData() {
    print('😴 睡眠控制器开始查询所有睡眠相关数据');

    // 调用所有睡眠相关的SDK接口
    _fetchAllSleepData();
  }

  /// 获取所有睡眠相关数据
  Future<void> _fetchAllSleepData() async {
    try {
      print('😴 开始获取所有睡眠数据...');

      // 【移除】不再手动调用 fetchSleepData()，因为：
      // 1. Kotlin 端的 fetchAllDeviceData() 会自动查询睡眠数据
      // 2. 避免重复调用 verifySleepDataGet 接口（会导致 4 次调用）
      // 3. 睡眠数据会通过监听器自动更新到 UI
      
      // 只需要等待数据回调即可
      print('⏳ 等待睡眠数据自动回调...');
      await Future.delayed(const Duration(milliseconds: 500));

      print('✅ 睡眠数据查询已触发，等待回调更新');
    } catch (e) {
      print('❌ 获取睡眠数据异常: $e');
      // 数据获取失败时显示错误状态
      _setErrorState('数据获取失败');
    }
  }

  /// 设置错误状态
  void _setErrorState(String errorMessage) {
    print('❌ 设置错误状态: $errorMessage');
    // 保持空值状态，不加载任何模拟数据
    _initializeEmptyState();
  }

  /// 设置睡眠数据监听器
  void _setupSleepDataListeners() {
    if (_listenersSetup) {
      print('👂 睡眠数据监听器已设置，跳过重复设置');
      return;
    }

    print('👂 开始设置睡眠数据监听器...');
    print('🔍 当前ringController睡眠数据状态: ${ringController.sleepData}');

    // 监听基础睡眠数据变化
    ever(ringController.sleepDataRx, (sleepData) {
      print('🔔 睡眠数据监听器触发！');
      if (sleepData != null) {
        print('😴 收到真实睡眠数据: ${sleepData.toString()}');
        print(
            '📊 睡眠数据详情: 总时长=${sleepData.totalSleepTime}分钟, 质量评分=${sleepData.qualityScore}');
        updateSleepDataFromRealData(sleepData);
      } else {
        print('📭 收到空的睡眠数据');
      }
    });

    _listenersSetup = true;
    print('✅ 睡眠数据监听器设置完成');
  }

  /// 从真实数据更新睡眠状态
  void updateSleepDataFromRealData(SleepData sleepData) {
    print('😴 更新睡眠数据状态: ${sleepData.toString()}');

    try {
      // 更新每日睡眠数据
      _updateDailySleepDataFromReal(sleepData);

      // 更新睡眠质量评分
      state.dailySleepScore.value = sleepData.qualityScore;

      print('✅ 睡眠状态更新完成');
    } catch (e) {
      print('❌ 更新睡眠状态失败: $e');
      // 出错时设置错误状态，不使用模拟数据
      _setErrorState('数据解析失败');
    }
  }

  /// 从真实数据更新每日睡眠数据
  void _updateDailySleepDataFromReal(SleepData sleepData) {
    // 格式化睡眠时长显示
    final int totalMinutes = sleepData.totalSleepTime;
    final int hours = totalMinutes ~/ 60;
    final int minutes = totalMinutes % 60;

    state.dailySleepTime.value = '${hours}小时${minutes}分';
    state.dailyBedTime.value = state.dailySleepTime.value; // 暂时使用相同值

    print(
        '📊 每日睡眠数据已更新: 总时长=${totalMinutes}分钟, 格式化=${state.dailySleepTime.value}');
    print(
        '📊 深睡眠=${sleepData.deepSleepTime}分钟, 浅睡眠=${sleepData.lightSleepTime}分钟, REM=${sleepData.remSleepTime}分钟');
  }

  /// 开始睡眠记录
  void startSleepRecord() {
    state.isRecording.value = true;
    state.sleepText.value = '正在记录睡眠...';
    state.startTime.value = DateTime.now();
  }

  /// 停止睡眠记录
  void stopSleepRecord() {
    state.isRecording.value = false;
    state.sleepText.value = '睡眠记录已停止';
    final duration = DateTime.now().difference(state.startTime.value);
    state.duration.value =
        '睡眠时长: ${duration.inHours}小时${duration.inMinutes % 60}分钟';
  }

  /// 刷新睡眠数据
  void refreshSleepData() {
    print('😴 手动刷新所有睡眠数据');

    if (ringController.isConnected) {
      // 【修改】直接调用 Kotlin 端的 fetchAllDeviceData()，避免重复调用
      // 这样只会触发一次 queryHistorySleepList()
      ringController.fetchAllDeviceData();
      Toast.show('正在查询最新睡眠数据...');
    } else {
      // 设备未连接时显示提示
      Toast.show('设备未连接，请先连接设备');
      _setErrorState('设备未连接');
    }
  }

  /// 强制刷新睡眠数据（即使设备未连接也尝试获取）
  void forceRefreshSleepData() {
    print('🔄 强制刷新睡眠数据');

    // 【修改】直接调用 Kotlin 端的 fetchAllDeviceData()
    ringController.fetchAllDeviceData();
    Toast.show('正在强制刷新睡眠数据...');
  }

  /// 获取设备序列号（优先使用当前连接的设备，否则使用上次连接的设备）
  String _getDeviceSn() {
    try {
      final deviceSnManager = Get.find<DeviceSnManager>();
      return deviceSnManager.getDeviceSn();
    } catch (e) {
      print('⚠️ 无法获取DeviceSnManager: $e');
      return '';
    }
    //   if (lastDevice != null && lastDevice.deviceSn.isNotEmpty) {
    //     print('📱 使用上次连接的设备SN: ${lastDevice.deviceSn}');
    //     return lastDevice.deviceSn;
    //   }
    // } catch (e) {
    //   print('⚠️ 无法获取DeviceStorageService: $e');
    // }

    // return '';
  }

  /// 加载睡眠详情数据
  Future<void> _loadSleepDetailData() async {
    print('😴 SleepController: _loadSleepDetailData 开始执行');

    final deviceSn = _getDeviceSn();
    print('📱 SleepController: 获取到的设备SN: ${deviceSn.isEmpty ? "空" : deviceSn}');

    if (deviceSn.isEmpty) {
      print('⚠️ SleepController: 无法获取设备序列号，跳过睡眠详情数据加载');
      print('💡 提示: 请确保设备已连接或之前有连接记录');
      return;
    }

    // 获取今天的日期
    final now = DateTime.now();
    final dateStr =
        '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

    print('📅 SleepController: 查询日期: $dateStr, type: 1 (日数据)');
    print('🔄 SleepController: 开始并行加载所有睡眠详情数据...');

    // 并行加载所有睡眠详情数据，默认 type=1 表示日数据
    const int type = 1;
    await Future.wait([
      _loadSleepInfoByType(deviceSn, dateStr, type),
      _loadSleepQualityScore(deviceSn, dateStr),
      _loadSleepProportionByType(deviceSn, dateStr, type),
      _loadSleepActivityStatusByType(deviceSn, dateStr,type),
      _loadSleepTrendByType(deviceSn, dateStr, type),
      _loadSleepHeartRateByType(deviceSn, dateStr, type),
      _loadSleepHrvByType(deviceSn, dateStr, type),
      _loadSleepBloodOxygenByType(deviceSn, dateStr, type),
      _loadShortSleepByType(deviceSn, dateStr, type),
    ]);

    print('✅ SleepController: 所有睡眠详情数据加载完成');
  }

  /// 加载睡眠质量评分
  Future<void> _loadSleepQualityScore(String deviceSn, String dateStr) async {
    try {
      print('📊 SleepController: 开始加载睡眠质量评分，日期: $dateStr');

      final response = await DefaultApi().queryQualityScoreGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final qualityData = SleepQualityScoreData.fromJson(data);
          state.updateSleepQualityData(qualityData);

          // 更新睡眠评分
          state.dailySleepScore.value = qualityData.sleepScore;

          // 更新睡眠潜伏期
          state.dailySleepLatency.value = qualityData.sleepLatency;

          print('✅ SleepController: 睡眠质量评分加载成功，评分: ${qualityData.sleepScore}');
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠质量评分失败: $e');
    }
  }

  

  /// 刷新睡眠详情数据（供外部调用）
  Future<void> refreshSleepDetailData() async {
    await _loadSleepDetailData();
  }

  /// 加载指定日期的睡眠详情数据（从日历返回时使用，type=1表示日数据）
  Future<void> loadSleepDataByDate(String dateStr) async {
    print('😴 SleepController: 加载指定日期的睡眠数据: $dateStr');

    final deviceSn = _getDeviceSn();
    print('📱 SleepController: 获取到的设备SN: ${deviceSn.isEmpty ? "空" : deviceSn}');

    if (deviceSn.isEmpty) {
      print('⚠️ SleepController: 无法获取设备序列号，跳过睡眠详情数据加载');
      Toast.show('无法获取设备信息');
      return;
    }

    print('📅 SleepController: 查询日期: $dateStr, type: 1 (日数据)');
    print('🔄 SleepController: 开始并行加载所有睡眠详情数据...');

    // 并行加载所有睡眠详情数据，传入 type=1 表示日数据
    const int type = 1;
    await Future.wait([
      _loadSleepInfoByType(deviceSn, dateStr, type),
      _loadSleepQualityScoreByType(deviceSn, dateStr, type),
      _loadSleepProportionByType(deviceSn, dateStr, type),
      _loadSleepActivityStatusByType(deviceSn, dateStr, type),
      _loadSleepTrendByType(deviceSn, dateStr, type),
      _loadSleepHeartRateByType(deviceSn, dateStr, type),
      _loadSleepHrvByType(deviceSn, dateStr, type),
      _loadSleepBloodOxygenByType(deviceSn, dateStr, type),
      _loadShortSleepByType(deviceSn, dateStr, type),
    ]);

    print('✅ SleepController: 指定日期的睡眠详情数据加载完成');
  }

  /// 检查是否有设备连接记录
  bool _hasDeviceRecord() {
    try {
      final deviceStorage = Get.find<DeviceStorageService>();
      final lastDevice = deviceStorage.lastConnectedDevice;
      return lastDevice != null && lastDevice.deviceSn.isNotEmpty;
    } catch (e) {
      print('⚠️ 无法获取DeviceStorageService: $e');
      return false;
    }
  }


  /// 根据类型加载睡眠数据（type: 1=日, 2=周, 3=月）
  Future<void> loadSleepDataByType(int type) async {
    print('😴 SleepController: 根据类型加载睡眠数据，type: $type');

    final deviceSn = _getDeviceSn();
    if (deviceSn.isEmpty) {
      print('⚠️ SleepController: 无法获取设备序列号');
      Toast.show('无法获取设备信息');
      return;
    }

    // 获取当前日期
    final now = DateTime.now();
    final dateStr =
        '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

    print('📅 SleepController: 查询日期: $dateStr, type: $type');

    // 根据type加载对应的数据
    await Future.wait([
      _loadSleepInfoByType(deviceSn, dateStr, type),
      _loadSleepQualityScoreByType(deviceSn, dateStr, type),
      _loadSleepProportionByType(deviceSn, dateStr, type),
      _loadSleepActivityStatusByType(deviceSn, dateStr, type),
      _loadSleepTrendByType(deviceSn, dateStr, type),
      _loadSleepHeartRateByType(deviceSn, dateStr, type),
      _loadSleepHrvByType(deviceSn, dateStr, type),
      _loadSleepBloodOxygenByType(deviceSn, dateStr, type),
      _loadShortSleepByType(deviceSn, dateStr, type),
    ]);

    print('✅ SleepController: type=$type 的睡眠数据加载完成');
  }

  /// 根据类型加载睡眠信息
  Future<void> _loadSleepInfoByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().sleepHomeQueryInfoGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type.toString(),
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final sleepInfo = SleepInfoData.fromJson(data);
          state.updateSleepInfoData(sleepInfo);
          
          // 根据type更新对应的睡眠时长
          switch (type) {
            case 1:
              state.dailySleepTime.value = sleepInfo.sleepDuration;
              break;
            case 2:
              state.weeklySleepTime.value = sleepInfo.sleepDuration;
              break;
            case 3:
              state.monthlySleepTime.value = sleepInfo.sleepDuration;
              break;
          }
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠信息失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠质量评分
  Future<void> _loadSleepQualityScoreByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().queryQualityScoreGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final qualityData = SleepQualityScoreData.fromJson(data);
          state.updateSleepQualityData(qualityData);
          
          // 根据type更新对应的评分
          switch (type) {
            case 1:
              state.dailySleepScore.value = qualityData.sleepScore;
              state.dailySleepLatency.value = qualityData.sleepLatency;
              break;
            case 2:
              state.weeklySleepScore.value = qualityData.sleepScore;
              state.weeklySleepLatency.value = qualityData.sleepLatency;
              break;
            case 3:
              state.monthlySleepScore.value = qualityData.sleepScore;
              state.monthlySleepLatency.value = qualityData.sleepLatency;
              break;
          }
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠质量评分失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠比例
  Future<void> _loadSleepProportionByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().queryProportionGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type.toString(),
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final proportionData = SleepProportionData.fromJson(data);
          state.updateSleepProportionData(proportionData);
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠比例失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠活动状态
  Future<void> _loadSleepActivityStatusByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().querySleepActivityStatusGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final activityData = SleepActivityStatusData.fromJson(data);
          state.updateSleepActivityData(activityData);
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠活动状态失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠趋势
  Future<void> _loadSleepTrendByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().querySleepTrendGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type.toString(),
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final trendData = SleepTrendData.fromJson(data);
          state.updateSleepTrendData(trendData);
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠趋势失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠心率
  Future<void> _loadSleepHeartRateByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().querySleepHeartRateGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type.toString(),
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final heartRateData = SleepMetricData.fromJson(data);
          state.updateSleepHeartRateData(heartRateData);
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠心率失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠心率变异性
  Future<void> _loadSleepHrvByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().querySleepHrvGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final hrvData = SleepMetricData.fromJson(data);
          state.updateSleepHrvData(hrvData);
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠心率变异性失败 (type=$type): $e');
    }
  }

  /// 根据类型加载睡眠血氧
  Future<void> _loadSleepBloodOxygenByType(String deviceSn, String dateStr, int type) async {
    try {
      final response = await DefaultApi().querySleepBOGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type.toString(),
        isShowLoading: false,
        isShowErrMsg: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          final boData = SleepMetricData.fromJson(data);
          state.updateSleepBloodOxygenData(boData);
        }
      }
    } catch (e) {
      print('❌ SleepController: 加载睡眠血氧失败 (type=$type): $e');
    }
  }

  /// 根据类型加载小睡数据
  Future<void> _loadShortSleepByType(String deviceSn, String dateStr, int type) async {
    try {
      print('📊 SleepController: 开始加载小睡数据，日期: $dateStr, type: $type');

      final response = await DefaultApi().queryShortSleepGet<dynamic>(
        deviceSn: deviceSn,
        dailyValue: dateStr,
        type: type,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      print('📊 SleepController: 小睡数据完整响应: $response');

      if (response != null && response['code'] == 200) {
        var data = response['data'];
        print('📊 SleepController: 第一层 data: $data');
        print('📊 SleepController: data 类型: ${data.runtimeType}');
        
        // 处理嵌套的 data 结构
        if (data != null && data is Map) {
          print('📊 SleepController: data 是 Map，检查是否有嵌套的 code');
          if (data['code'] == 200) {
            print('📊 SleepController: 发现嵌套的 code=200，提取内层 data');
            data = data['data'];
            print('📊 SleepController: 内层 data: $data');
          }
        }
        
        if (data != null) {
          print('📊 SleepController: 准备解析小睡数据');
          print('📊 SleepController: sleepDuration = ${data['sleepDuration']}');
          print('📊 SleepController: shortSleepDates = ${data['shortSleepDates']}');
          
          final shortSleepData = ShortSleepData.fromJson(data as Map<String, dynamic>);
          state.updateShortSleepData(shortSleepData);
          
          print('✅ SleepController: 小睡数据加载成功');
          print('✅ 平均时长: ${shortSleepData.sleepDuration}');
          print('✅ 日期数量: ${shortSleepData.shortSleepDates.length}');
          if (shortSleepData.shortSleepDates.isNotEmpty) {
            print('✅ 第一天: ${shortSleepData.shortSleepDates.first.dailyValue}');
            print('✅ 第一天小睡次数: ${shortSleepData.shortSleepDates.first.shortSleepTimes?.length ?? 0}');
          }
        } else {
          print('⚠️ SleepController: data 为 null');
        }
      } else {
        print('⚠️ SleepController: 响应为 null 或 code != 200');
      }
    } catch (e, stackTrace) {
      print('❌ SleepController: 加载小睡数据失败 (type=$type): $e');
      print('❌ 堆栈跟踪: $stackTrace');
    }
  }
}
